import React, { memo, useEffect, useRef, useState } from 'react'
import { ScollViewWrapper } from './style'
import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'
// 控制一系列元素的显示 通过前后按钮 实现元素的滚动 无法滚动按钮消失
const ScollView = memo((props) => {
  const [positionIndex, setPositionIndex] = useState(0)
  const [showLeft, setShowLeft] = useState(false)
  const [showRight, setShowRight] = useState(false)
  const contentRef = useRef()
  const totalDistance = useRef()
  useEffect(() => {
    const scrollWidth = contentRef.current.scrollWidth
    const clientWidth = contentRef.current.clientWidth
    totalDistance.current = scrollWidth - clientWidth
    setShowRight(totalDistance.current > 0)
  }, [props.children])
  function clickHandler(isRight){
    const next = isRight ? positionIndex + 1 : positionIndex - 1
    const offsetLeft = contentRef.current.children[next].offsetLeft
    contentRef.current.style.transform = `translate(-${offsetLeft}px)`
    setPositionIndex(next)
    setShowLeft(offsetLeft > 0)
    setShowRight(offsetLeft < totalDistance.current)
  }
  return (
    <ScollViewWrapper>
       {showLeft &&  (
        <div className='control left' onClick={e => clickHandler(false)}>
            <IconArrowLeft/>
        </div>
       )}
       {showRight && (
        <div className='control right' onClick={e => clickHandler(true)}>
            <IconArrowRight/>
        </div>
       )}
        <div className='content'>
            <div className='scoll-content' ref={contentRef}>
                {props.children}
            </div>
        </div>
    </ScollViewWrapper>
  )
})


export default ScollView